﻿using System;
using System.Collections.Generic;

using System.Text;

namespace DotNETX.Authentication
{
    public class BasicExclusiveLoginTokenManager : DotNETX.Authentication.ITokenManager
    {
        #region ITokenManager

        public string New()
        {
            return Guid.NewGuid().ToString();
        }

        private UserSession FindSession(IEnumerable<UserSession> sessions, object uniqueId)
        {
            foreach (UserSession us in sessions)
            {
                if (us.UniqueId.GetHashCode() == uniqueId.GetHashCode()) return us;
            }
            return null;
        }

        public int Register(string token, object uniqueId)
        {
            if (token == null || uniqueId == null) return -1;
            if (Map.ContainsKey(token)) return -2;
            UserSession userSession = null;
            try
            {

                if (null != (userSession = FindSession(Map.Values, uniqueId)))
                {
                    lock (Map)
                    {
                        Map.Remove(userSession.Token);
                        Map.Add(token, new UserSession() { Token = token, UniqueId = uniqueId, LoginTime = DateTime.Now, LastVistTime = DateTime.Now });
                        return 0;
                    }
                }
                else
                {
                    lock (Map)
                    {
                        Map.Add(token, new UserSession() { Token = token, UniqueId = uniqueId, LoginTime = DateTime.Now, LastVistTime = DateTime.Now });
                        return 0;
                    }
                }
            }
            catch (Exception ex)
            {
                return int.MinValue;
            }
        }

        public int Unregister(string token)
        {
            if (token == null) return -1;
            if (!Map.ContainsKey(token)) return -2;
            try
            {
                lock (Map)
                {
                    Map.Remove(token);
                    return 0;
                }
            }
            catch (Exception ex)
            {
                return int.MinValue;
            }
        }

        public UserSession GetSession(string token)
        {
            if (token == null) return null;
            if (!Map.ContainsKey(token)) return null;
            else
            {
                lock (Map[token])
                {
                    Map[token].LastVistTime = DateTime.Now;
                }
                return Map[token];
            }
        }

        #endregion

        public BasicExclusiveLoginTokenManager()
        {
            Map = new Dictionary<string, UserSession>();
        }

        public Dictionary<string, UserSession> Map { get; private set; }
    }
}
